package com.trickytriads.model.datastore
{
	import com.adobe.utils.DictionaryUtil;
	import com.trickytriads.events.GetAllCardsEvent;
	import com.trickytriads.model.CardData;
	
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	
	/**
	 * CardDataStore
	 * 
	 * Singleton class that functions as a CardData dictionary, associating card ids to actual
	 * card data.
	 * 
	 * Parsley handles making this a singleton.
	 **/	 
	public class CardDataStore
	{
		// Card dictionary <uint, CardData>
		private var _dict:Dictionary;
		
		// Constructor, initializes the singleton instance.
		public function CardDataStore() 
		{
		}		
		
		/**
		 * Message handler that is called when all cards are loaded.
		 * Adds them all to the dictionary.
		 */
		[MessageHandler(selector="getAllCardsDone")]
		public function storeCardData (evt:GetAllCardsEvent) : void
		{
			// Clear out and/or create dictionary
			if (_dict == null)
				_dict = new Dictionary();
			
			// trace("Adding CardData to dictionary" + evt._cards.length);
			if (evt._cards == null)
			{
				Alert.show("_cards in GetAllCardsEvent was null");
			}
			for (var i:uint = 0; i < evt._cards.length; i++)
			{			
				var cd:CardData = evt._cards[i] as CardData;
				// trace("Pushing card_id: " + cd.card_id.toString());
				_dict[cd.card_id.toString()] = cd;
				// trace("Result: " + (_dict[cd.card_id.toString()] as CardData).card_id.toString());
			}
		}
		
		/**
		 * Gets a card from the card dictionary.
		 */
		public function getCard (id:uint) : CardData
		{
			return (_dict[id] as CardData);
		}
			
		
		/**
		 * Gets a list (well, Array, really) of <code>num</code> cards, starting
		 * at <code>start</code>.  Order parameter will become a sort order.
		 */
		public function getCardList (start:uint, num:uint, order:String = null) : ArrayCollection
		{
			// Get an array of card values
			var carddataValues:Array = DictionaryUtil.getValues(_dict);
			var returnArray:Array = new Array();
			for (var i:uint = start; i < num; i++)
			{
				// If our index is out of range push null, otherwise push the card
				if (i > carddataValues.length || carddataValues[i] == null)
				{
					trace("Pushing a null value");
					returnArray.push(null);
				}
				else				
				{	
					trace("Pushing " + (carddataValues[i] as CardData).card_id);				
					returnArray.push(carddataValues[i]);
				}
			}
						
			return new ArrayCollection(returnArray);
		}
	}
}